/*
	klib_IRQ_control.h

	contains headers for IRQ routing and handling setup

	Author: Aidan Goddard 5/10/13
*/

#ifndef KLIB_IRQ_CONTROL_H_INCLUDED
#define KLIB_IRQ_CONTROL_H_INCLUDED

typedef uint32_t ISR_VECTOR;

uint32_t	__KLIB__ISRReserve(uint32_t priority, const uint32_t consec_count, ISR_VECTOR *vectors, uint64_t *keys);
uint32_t	__KLIB__ISRFree(ISR_VECTOR vector, uint64_t key);

uint32_t	__KLIB__ISRRegister(ISR_VECTOR vector, uint64_t key, void (*isr)(uint32_t vector), uint8_t CPL, uint8_t gate, uint8_t stack);
uint32_t	__KLIB__ISRUnregister(ISR_VECTOR vector, uint64_t key);

uint32_t	__KLIB__GetGSIFromISA(uint32_t ISA_vector, uint32_t *GSI, uint32_t *polarity, uint32_t *trigger_mode);

uint32_t	__KLIB__GSIReserve(uint32_t GSI, uint64_t *key);
uint32_t	__KLIB__GSIFree(uint32_t GSI, uint64_t key);

uint32_t	__KLIB__IOAPIC_mask_IRQ(uint32_t GSI, uint64_t key);
uint32_t	__KLIB__IOAPIC_unmask_IRQ(uint32_t GSI, uint64_t key);
uint32_t	__KLIB__IOAPIC_get_IRQ_reg_dump(uint32_t GSI, uint64_t key, uint64_t *buffer);
uint32_t	__KLIB__IOAPIC_manual_reg_write(uint32_t GSI, uint64_t key, ISR_VECTOR vector, uint32_t polarity, uint32_t trigger_mode);

uint32_t	__KLIB__GetMSIDestination(uint32_t *message_address_register);

// input values
#define IRQ_IST_NO_STACK		0
#define IRQ_IST_1				1
#define IRQ_IST_2				2
#define IRQ_IST_3				3
#define IRQ_IST_4				4
#define IRQ_IST_5				5
#define IRQ_IST_6				6
#define IRQ_IST_7				7

#define IRQ_CPL_KERNEL			0
#define IRQ_CPL_USER			3

#define IRQ_GATE_TRAP			0xf
#define IRQ_GATE_INTERRUPT		0xe

// trigger mode and polarity internal values
// (note these may not correspond directly to values that are written to hardware)
#define IRQ_IN_TRIGGER_MODE_EDGE	1
#define IRQ_IN_TRIGGER_MODE_LEVEL	0
#define IRQ_IN_POLARITY_HIGH		1
#define IRQ_IN_POLARITY_LOW			0


// returned error codes
#define IRQ_SUCCESS				0
#define IRQ_NO_ISR_IN_PRIORITY	0xffffffff
#define IRQ_BAD_STACK_NUMBER	0xfffffffe
#define IRQ_BAD_CPL_NUMBER		0xfffffffd
#define IRQ_BAD_GATE_NUMBER		0xfffffffc
#define IRQ_BAD_ISA_VECTOR		0xfffffffb
#define IRQ_GSI_NOT_AVAILABLE	0xfffffffa
#define IRQ_GSI_NOT_RESERVED	0xfffffff9
#define IRQ_BAD_GSI				0xfffffff8
#define IRQ_BAD_PRIORITY_NUMBER	0xfffffff7
#define IRQ_ISA_NOT_MAPPED		0xfffffff6
#define IRQ_GSI_NOT_MAPPED		0xfffffff5
#define IRQ_BAD_VECTOR			0xfffffff4
#define IRQ_VEC_NOT_AVAILABLE	0xfffffff3
#define IRQ_VEC_NOT_RESERVED	0xfffffff2
#define IRQ_GSI_KEY_INVALID		0xfffffff1
#define IRQ_VEC_KEY_INVALID		0xfffffff0
#define IRQ_GSI_SYSTEM_OWNED	0xffffffef
#define IRQ_BAD_COUNT			0xffffffee
#define IRQ_BAD_ISR_ADDRESS		0xffffffed

#endif
